package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author tongchen
 * @create 2023-01-04 10:59
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //定义匹配器
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //获取请求路径
        String requestURI = request.getRequestURI();
        //定义拦截请求数组
        String []url={"/employee/login","/employee/logout","/backend/**","/front/**","/page/**","/common/upload","/common/download"
        ,"user/sendMsg","/user/login"};
        //返回结果
        log.info("拦截到的uri:{}",requestURI);
        if(check(url,requestURI)){
            //放行
            filterChain.doFilter(request,response);
            log.info("放行的uri{}",requestURI);
            return;
        }
        //页面跳转
        //判断登录状态，如果登录直接跳过
        if(request.getSession().getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            //已经登录的uri
            log.info("已经登录，id为:{}",request.getSession().getAttribute("employee"));
            //获取id并存储线程
            Long employee = (Long) request.getSession().getAttribute("employee");
            BaseContext.setThreadLocalId(employee);
            return;
        }
        if(request.getSession().getAttribute("user")!=null){
            filterChain.doFilter(request,response);
            //已经登录的uri
            log.info("已经登录，id为:{}",request.getSession().getAttribute("user"));
            //获取id并存储线程
            Long user = (Long) request.getSession().getAttribute("user");
            BaseContext.setThreadLocalId(user);
            return;
        }
        //拦截跳转
        log.info("拦截跳转");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 匹配提供的uri是否在uris范围内
     * @param urls
     * @param requestURI
     * @return
     */

    //定义匹配方法
    public boolean check(String[]urls,String requestURI){
        for (String url:urls) {
           if(PATH_MATCHER.match(url,requestURI)){
                return true;
            }
        }
        return false;
    }
}
